package stool.juc.ordernotifier;

import java.util.Objects;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 题目：多线程之间按顺序调用，实现A->B->C
 * 三个线程启动，要求如下：
 * AA打印5次，BB打印10次，CC打印15次
 * 接着
 * AA打印5次，BB打印10次，CC打印15次
 * 来10轮
 * @author Felix YF Dong
 * @Description
 * @Date 2023/2/17
 */
public class OrderNorifier {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.print5();
            }
        }, "5A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.print10();
            }
        }, "10B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareData.print15();
            }
        }, "15C").start();
    }

}

class ShareData {
    private int number = 1;
    private Lock locker = new ReentrantLock();
    private Condition c1 = locker.newCondition();
    private Condition c2 = locker.newCondition();
    private Condition c3 = locker.newCondition();

    public void print5() {
        locker.lock();
        try {
            while (!Objects.equals(number, 1)) {
                c1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "~" + ( i + 1));
            }
            number = 2;
            c2.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            locker.unlock();
        }
    }

    public void print10() {
        locker.lock();
        try {
            while (!Objects.equals(number, 2)) {
                c2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "~" + (i + 1));
            }
            number = 3;
            c3.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            locker.unlock();
        }
    }

    public void print15() {
        locker.lock();
        try {
            while (!Objects.equals(number, 3)) {
                c3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "~" + (i + 1));
            }
            number = 1;
            c1.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            locker.unlock();
        }
    }
}







